import {
	getBaseApi
} from './config.js'
const TokenRequest = (opts, data) => {
	let access_token = app.globalData.userInfo;
	//此token是登录成功后存在全局
	let DefaultOpts = {
		url: getBaseApi().baseUrl1 +opts.url,
		data: data,
		method: opts.method,
		header: opts.method == 'get' ? {'access-token': access_token,'X-Requested-With': 'XMLHttpRequest',"Accept": "application/json","Content-Type": "application/json;charset=UTF-8"} : {'access-token': access_token,'X-Requested-With': 'XMLHttpRequest','Content-Type': 'application/json;charset=UTF-8'},
		dataType: 'json',
	}
	let promise = new Promise(function(resolve, reject) {
		wx.request(DefaultOpts).then(
			(res) => {
				let results = res[1]
				if (results.statusCode === 200 && results.data.code === 9996){
				
					wx.redirectTo({
					    url: '/pages/login'
					});
				}
				if (results.statusCode !== 200) {
					console.log(results)
					wx.showToast({
						icon:'none',
					    title: (results.data.message || '发生异常错误'),
					    duration: 3000 
					});
					return false
				}
				resolve(results.data)
			}
		).catch(
			(response) => {
				reject(response)
			}
		)
	})
	return promise
}

const post = (url, data) => {
	return TokenRequest({url: url, method: "post"}, data)
}

const get = (url) => {
	return TokenRequest({url: url, method: "get"}, {})
}

const deletes = (url) => {
	return TokenRequest({url: url, method: "delete"})
}

/** 输出 */
export default {
	post,
	get,
	deletes
}